//
//  SQliteManager.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/22.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import Foundation
private let dbName = "readMe.db"
class SQliteManager {
     static let shareManager = SQliteManager()
     let queue: FMDatabaseQueue
     private  init(){
        var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
        
        path = (path as NSString).stringByAppendingPathComponent(dbName)
        queue = FMDatabaseQueue(path: path)
        createTable()
    }
    
     func execRecordSet(sql:String)->[[String: AnyObject]]{
        
        var result = [[String: AnyObject]]()
        queue.inDatabase { (db) -> Void in
            guard let rows =   db.executeQuery(sql) else{
                return
            }
            while rows.next(){
                var dict = [String: AnyObject]()
                let colCount = rows.columnCount()
                for i in 0..<colCount{
                   let name = rows.columnNameForIndex(i)
                   let obj = rows.objectForColumnName(name)
                    dict[name] = obj
                }
                result.append(dict)
                
            }
            
        }
        
        return result
    }
    
    private func createTable(){
        let path = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)
        let sql = try! String(contentsOfFile: path!)
        queue.inDatabase { (db) -> Void in
            if db.executeStatements(sql) {
                print("创建表格成功")
            }else{
                print("创建表格失败")
            }
        }
        
    }
}